
class SparseMatrix {
    // size: [number_rows, number_cols]
    constructor(size) {
        this.val = math.random(size);
        this.rows = size[0];
        this.cols = size[1];
    }

    // pos: [index_row, index_col]
    // 如果元素不存，返回0
    get(pos) {
        //...
    }
    // pos: [index_row, index_col]
    set(pos, value) {
        //...
    }

}


// 随机填充稀疏矩阵
// 该函数用做概念展演示，实际生成效率并不高。
// 请同学们思考一下为什么效率不高？
// 参数：
// m: SparseMatrix
// density: 稀疏矩阵的密度
function fillMatrix(m, density) {
    const target_elements = density * m.rows * m.cols;
    let count = 0;
    while(count < target_elements) {
        let random_row = math.randomInt(0, rows);
        let random_col = math.randomInt(0, cols);
        if(m.get([random_row, random_col]) == 0) {
            m.set([random_row, random_col], math.random());
            count++;
        }
    }
}

// 矩阵相乘运算
// 输入两个矩阵，返回相乘之后的结果
function multiply(matrix_a, matrix_b) {

}

const rows = 100;
const cols = 100;
const density_a = 0.01;
const density_b = 0.03;
const matrix_a = new SparseMatrix([rows, cols]);
const matrix_b = new SparseMatrix([rows, cols]);

// 填充稀疏矩阵
console.log("start to fill sparse matrix...")
let start = performance.now();
fillMatrix(matrix_a, density_a);
fillMatrix(matrix_b, density_b);
console.log("finished. Use " + (performance.now() - start) / 1000 + " secs");

// 矩阵相乘
console.log("start to sparse matrix multiplication...")
start = performance.now();
let matrix_c = multiply(matrix_a, matrix_b);
console.log("finished. Use " + (performance.now() - start) / 1000 + " secs");


// 与标准库做对比验证
// 复制成为标准矩阵
function createDenseMatrix(m) {
    const matrix_std = math.zeros([rows, cols]);
    for(let i = 0; i < rows; i++) {
        for(let j = 0; j < cols; j++) {
            if(m.get([i, j]) != 0) {
                matrix_std.set([i, j], m.get([i, j]))
            }
        }
    }
    return matrix_std
}

// 复制成为标准稀疏矩阵
function createSparseMatrix(m) {
    const matrix_std_sparse = math.zeros([rows, cols], 'sparse');
    for(let i = 0; i < rows; i++) {
        for(let j = 0; j < cols; j++) {
            if(m.get([i, j]) != 0) {
                matrix_std_sparse.set([i, j], m.get([i, j]))
            }
        }
    }
    return matrix_std_sparse;
}

